from odoo import fields, models, api, _
from datetime import date
from odoo.exceptions import UserError, ValidationError


class ConsignmentAllotLineWizard(models.TransientModel):
    _name = 'consignment.allot.line.wizard'
    product_id = fields.Many2one('product.template', string='Product')
    quantity = fields.Float(string='Quantity')
    onhand_qty = fields.Float(string='Onhand Quantity', compute='_compute_onhand_quantity')
    caw_id = fields.Many2one('consignment.allot.wizard')

    @api.depends('product_id')
    def _compute_onhand_quantity(self):
        if not self.product_id:
            self.onhand_qty = 0
            return 0
        for rec in self:
            rec.onhand_qty = self.env['stock.quant']._get_available_quantity(
                rec.product_id, self.env.ref('stock.stock_location_stock'))


class ConsignmentAllotWizard(models.TransientModel):
    _name = 'consignment.allot.wizard'

    consignment_id = fields.Many2one('consignment.sales',
                                     default=lambda self: self.env.context.get('consignment_id', False))
    product_id = fields.Many2one('product.template', string='Product',
                                 default=lambda self: self.env.context.get('product_id'))
    allot_qty = fields.Integer(string='Allot Qty')
    onhand_qty = fields.Float(string='Onhand Qty', compute='_compute_onhand_quantity', store=True)
    owe_qty = fields.Float(string='Owe Qty', default=lambda self: self.env.context.get('owe_qty'))

    @api.depends('product_id')
    def _compute_onhand_quantity(self):
        if not self.product_id:
            self.onhand_qty = 0
            return 0
        self.onhand_qty = self.env['stock.quant']._get_available_quantity(
            product_id=self.product_id.product_variant_id, location_id=self.env.ref('stock.stock_location_stock'))
        if self.onhand_qty <= 0:
            raise ValidationError(_('Insufficient stock'))

    def confirmation(self):
        # Confirm the creation of the transfer record.
        for line in self:
            if line.allot_qty > line.onhand_qty or line.allot_qty <= 0:
                raise ValidationError('Insufficient stock')
            sp_id = self.env['stock.picking'].create({
                'partner_id': line.consignment_id.customer_id.id,
                'picking_type_id': self.env.ref('consignment.cs_stock_pick_type').id,
                'location_id': self.env.ref('stock.stock_location_stock').id,
                'location_dest_id': self.env.ref('consignment.cs_stock_location').id,
                'move_type': 'one',
                'consignment_id': line.consignment_id.id,
                'owner_id': line.consignment_id.customer_id.id,
                'origin': line.consignment_id.name
            })
            sm = self.env['stock.move'].create({
                'name': line.product_id.name,
                'product_id': line.product_id.product_variant_id.id,
                'product_uom_qty': line.allot_qty,
                'product_uom': line.product_id.uom_id.id,
                'location_id': sp_id.location_id.id,
                'location_dest_id': sp_id.location_dest_id.id,
                'picking_id': sp_id.id
            })
            self.env['consignment.sales.line'].create({
                'consignment_id': line.consignment_id.id,
                'product_id': line.product_id.id,
                'quantity': line.allot_qty,
                'state': 'hole',
                'stock_move_id': sm.id,
            })
            message_body = _('Created shipment for %s %s') % (line.allot_qty, line.product_id.name)
            self.consignment_id.message_post(body=message_body)
            return {
                'type': 'ir.actions.act_window',
                'name': 'Stock Picking',
                'res_model': 'stock.picking',
                'view_mode': 'form',
                'res_id': sp_id.id,
                'target': 'current',
                'views': [((False, 'form'))],
                'context': {'default_picking_type_id': self.env.ref('consignment.cs_stock_pick_type').id},
            }

    # line_ids = fields.One2many('consignment.allot.line.wizard', 'caw_id', string='Additional product')

    # def confirmation(self):
    #     for line in self.line_ids:
    #         if line.quantity > line.onhand_qty or line.quantity <= 0:
    #             raise ValidationError('Insufficient stock')
    #     sp_id = self.env['stock.picking'].create({
    #         # 'material_uom_id': 1,
    #         # 'alt_material_uom_id': 1,  ##???
    #         'partner_id': self.customer_id.id,
    #         'picking_type_id': self.env.ref('consignment.cs_stock_pick_type').id,
    #         'location_id': self.env.ref('stock.stock_location_stock').id,
    #         'location_dest_id': self.env.ref('consignment.cs_stock_location').id,
    #         'move_type': 'one',
    #         'consignment_id': self.consignment_id.id,
    #     })
    #     for line in self.line_ids:
    #         sm = self.env['stock.move'].create({
    #             'name': line.product_id.name,
    #             'product_id': line.product_id.id,
    #             'product_uom_qty': line.quantity,
    #             'product_uom': line.product_id.uom_id.id,
    #             'location_id': sp_id.location_id.id,
    #             'location_dest_id': sp_id.location_dest_id.id,
    #             'picking_id': sp_id.id
    #         })
    #         self.env['consignment.sales.line'].create({
    #             'consignment_id': self.consignment_id.id,
    #             'product_id': line.product_id.id,
    #             'quantity': line.quantity,
    #             'state': 'hole',
    #             'stock_move_id': sm.id
    #         })
    #     # 打开创建的移动记录窗口
    #     return {
    #         'type': 'ir.actions.act_window',
    #         'name': 'Stock Picking',
    #         'res_model': 'stock.picking',
    #         'view_mode': 'form',
    #         'res_id': sp_id.id,
    #         'target': 'current',
    #         'views': [((False, 'form'))],
    #         'context': {'default_picking_type_id': self.env.ref('consignment.cs_stock_pick_type').id},
    #     }
